package com.mtnz.njk.Service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.mtnz.njk.GexinUtil.PushMessageToAppDemo;
import com.mtnz.njk.Mapper.*;
import com.mtnz.njk.entity.*;
import com.mtnz.njk.model.IntegralStatisticsModel;
import com.mtnz.njk.model.ProductManagerListModel;
import com.mtnz.njk.model.ProductStatisticsModel;
import com.mtnz.njk.model.UpdateActiveProductModel;
import com.mtnz.njk.result.PageInfo;
import com.mtnz.njk.result.ResponseMessage;
import com.mtnz.njk.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 商品管理服务层
 * @Author: FBL
 * @CreateDate: 2019\8\12 0012 19:43
 * @Version: 1.0
 */
@Service
public class ProductManagerService {

    @Autowired
    ProductManagerMapper productManagerMapper;

    @Autowired
    ProductImgMapper productImgMapper;

    @Autowired
    ResearchManageMapper researchManageMapper;

    @Autowired
    ProductTypeMapper productTypeMapper;

    @Autowired
    ProductDetailTypeMapper productDetailTypeMapper;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    ProductRemarkMapper productRemarkMapper;

    @Autowired
    ProviderMapper providerMapper;

    @Autowired
    ResearchImgManageMapper researchImgManageMapper;

    @Autowired
    ProductActiveTypeMapper productActiveTypeMapper;

    @Autowired
    ProductActiveThresholdMapper productActiveThresholdMapper;

    @Autowired
    ProductActiveGiveMapper productActiveGiveMapper;

    @Autowired
    IntegralManagerMapper integralMapper;

    @Autowired
    IntegralTypeMapper integralTypeMapper;

    @Autowired
    CalendarMapper calendarMapper;

    @Autowired
    ComboMapper comboMapper;

    @Autowired
    NjkUserMapper userMapper;


    /**
     * 查询商品列表
     *
     * @return
     * @throws Exception
     */
    public ResponseResult listProduct(String key, Integer pageNum, Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        // 得到分页后的商品信息
        List<ProductManagerListModel> allProductList = productManagerMapper.getAllProductList(key);
        PageInfo<ProductManagerListModel> productManagerListModelPageInfo = new PageInfo<>(allProductList);

        List<ProductManagerListModel> productList = productManagerListModelPageInfo.getList();

        // 用于编辑页面展示类型信息
        List<ProductTypeEntity> productTypeEntities = productTypeMapper.selectAll();
        List<ProductDetailTypeEntity> productDetailTypeEntities = productDetailTypeMapper.selectAll();
        List<ProviderEntity> providerEntities = providerMapper.selectAll();

        for (ProductManagerListModel productManagerListModel : productList) {
            if (productManagerListModel.getCombo() == 1) {
                // 属于套餐，将套餐信息返回去
                Example comboExample = new Example(ComboEntity.class);
                comboExample.createCriteria().andEqualTo("productId", productManagerListModel.getProductId());
                List<ComboEntity> comboEntities = comboMapper.selectByExample(comboExample);

                ArrayList<ProductEntity> productEntities = new ArrayList<>();
                for (ComboEntity comboEntity : comboEntities) {
                    // 属于该套餐的商品id
                    String productId = comboEntity.getProductIdCombo();
                    // 查询商品信息
                    ProductEntity productEntity = productMapper.selectByPrimaryKey(productId);
                    productEntities.add(productEntity);
                }
                productManagerListModel.setComboEntity(productEntities);

            }

            String productId = productManagerListModel.getProductId();
            // 得到商品滚动图
            Example productImgExample = new Example(ProductImgEntity.class);
            productImgExample.createCriteria().andEqualTo("productId", productId);
            List<ProductImgEntity> productImgEntities = productImgMapper.selectByExample(productImgExample);
            productManagerListModel.setProductImg(productImgEntities);

            // 得到商品规格
            Example productRemarkExample = new Example(ProductRemarkEntity.class);
            productRemarkExample.createCriteria().andEqualTo("productId", productId);
            List<ProductRemarkEntity> productRemarkEntities = productRemarkMapper.selectByExample(productRemarkExample);
            productManagerListModel.setProductRemark(productRemarkEntities);
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("productList", productManagerListModelPageInfo);
        result.put("productType", productTypeEntities);
        result.put("provider", providerEntities);
        result.put("productDetailType", productDetailTypeEntities);
        return new ResponseResult(ResponseMessage.OK, result);
    }

    /**
     * 查询商品帖子
     *
     * @param key
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    public ResponseResult listProductResearch(String key, Integer pageNum, Integer pageSize, String productId) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        Example researchExample = new Example(ResearchEntity.class);
        Example.Criteria criteria = researchExample.createCriteria();
        criteria.andEqualTo("productId", productId);
        if (key != null && !("").equals(key)) {
            criteria.andLike("subject", "%" + key + "%");
        }
        // 分页模糊得到研究社数据
        List<ResearchEntity> researchEntities = researchManageMapper.selectByExample(researchExample);
        PageInfo<ResearchEntity> researchEntityPageInfo = new PageInfo<>(researchEntities);
        List<ResearchEntity> researchList = researchEntityPageInfo.getList();

        for (ResearchEntity researchEntity : researchList) {
            Integer researchId = researchEntity.getResearchId();
            // 得到研究社帖子封面图和分享图
            HashMap<String, String> researchImg = productManagerMapper.getResearchImg(researchId);
            if (researchImg != null && researchImg.containsKey("shareImg") && researchImg.containsKey("coverImg")) {
                String shareImg = researchImg.get("shareImg");
                String coverImg = researchImg.get("coverImg");
                researchEntity.setShareImg(shareImg);
                researchEntity.setCoverImg(coverImg);
            }
        }
        return new ResponseResult(ResponseMessage.OK, researchEntityPageInfo);
    }

    /**
     * 修改商品信息
     *
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult updateProduct(ProductManagerListModel productModel) throws Exception {

        if (productModel.getCombo() == 1) {
            // 去除以前的套餐商品信息
            String productId = productModel.getProductId();
            Example comboExample = new Example(ComboEntity.class);
            comboExample.createCriteria().andEqualTo("productId", productId);
            comboMapper.deleteByExample(comboExample);
            List<String> comboProductIds = productModel.getComboProductIds();
            for (String comboProductId : comboProductIds) {
                // 添加套餐商品
                ComboEntity comboEntity = new ComboEntity();
                // 套餐内的其他商品id
                comboEntity.setProductIdCombo(comboProductId);
                comboEntity.setProductId(productModel.getProductId());
                comboEntity.setSort(productModel.getSort());
                comboMapper.insert(comboEntity);
            }
        }

        // 商品id
        String productId = productModel.getProductId();
        // 得到商品信息
        ProductEntity productEntity = productMapper.selectByPrimaryKey(productId);
        if (productEntity != null) {
            productEntity.setBigImg(productModel.getBigImg());
            productEntity.setTypeId(productModel.getProductTypeId());
            productEntity.setDetailTypeId(productModel.getProductDetailTypeId() + "");
            productEntity.setProductName(productModel.getProductName());
            productEntity.setRemarks(productModel.getRemarks());
            productEntity.setSort(productModel.getSort());
            productEntity.setProviderName(productModel.getProviderName());
            productEntity.setProviderPhone(productModel.getProviderPhone());
            productEntity.setRepertoryNum(productModel.getRepertoryNum());
            productEntity.setProvider(productModel.getProviderId());
            productEntity.setSoldFlag(productModel.getSoldFlag() + "");
            productEntity.setPostage(productModel.getPostage());
            productEntity.setCombo(productModel.getCombo());
            // 展示价格 ？？？？
            //是否是活动商品？？？？
            productEntity.setActiveImg(productModel.getActiveUrl());
            // 测试产品？？
            productEntity.setVideoUrl(productModel.getVideoUrl());
            productEntity.setImg(productModel.getImg());
            productEntity.setResearchTopImg(productModel.getResearchImg());
            productEntity.setComboImg(productModel.getComboImg());
            productEntity.setDetails(productModel.getDetails());

            productMapper.updateByPrimaryKeySelective(productEntity);
            return new ResponseResult(ResponseMessage.OK);
        }
        return new ResponseResult(ResponseMessage.FAIL, "该商品不存在");
    }

    /**
     * 新增商品信息
     *
     * @param productModel
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult insertProduct(ProductManagerListModel productModel) throws Exception {
        if (productModel.getCombo() == 1) {
            List<String> comboProductIds = productModel.getComboProductIds();
            for (String comboProductId : comboProductIds) {
                // 添加套餐商品
                ComboEntity comboEntity = new ComboEntity();
                // 套餐内的其他商品id
                comboEntity.setProductIdCombo(comboProductId);
                comboEntity.setProductId(productModel.getProductId());
                comboEntity.setSort(productModel.getSort());
                comboMapper.insert(comboEntity);
            }

        }

        ProductEntity productEntity = new ProductEntity();

        String id = IdUtil.simpleUUID();
        productEntity.setProductId(id);

        productEntity.setTypeId(productModel.getProductTypeId());
        productEntity.setDetailTypeId(productModel.getProductDetailTypeId() + "");
        productEntity.setProductName(productModel.getProductName());
        productEntity.setRemarks(productModel.getRemarks());
        productEntity.setSort(productModel.getSort());
        productEntity.setProviderName(productModel.getProviderName());
        productEntity.setProviderPhone(productModel.getProviderPhone());
        productEntity.setRepertoryNum(productModel.getRepertoryNum());
        productEntity.setProvider(productModel.getProviderId());
        productEntity.setSoldFlag(productModel.getSoldFlag() + "");
        productEntity.setPostage(productModel.getPostage());
        productEntity.setCombo(productModel.getCombo());
        productEntity.setShareViews(0);
        // 展示价格 ？？？？
        //是否是活动商品？？？？
        productEntity.setActiveImg(productModel.getActiveUrl());
        // 测试产品？？
        productEntity.setVideoUrl(productModel.getVideoUrl());
        productEntity.setImg(productModel.getImg());
        productEntity.setResearchTopImg(productModel.getResearchImg());
        productEntity.setComboImg(productModel.getComboImg());
        productEntity.setDetails(productModel.getDetails());
        productEntity.setBigImg(1);
        productEntity.setCreateTime(DateUtil.now());
        productMapper.insert(productEntity);

        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 商品滚动图的添加
     *
     * @param productId
     * @param productImg
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult insertProductImg(String productId, String productImg) throws Exception {
        String id = IdUtil.simpleUUID();
        ProductImgEntity productImgEntity = new ProductImgEntity();
        productImgEntity.setProductImgId(id);
        productImgEntity.setProductId(productId);
        productImgEntity.setProductImg(productImg);
        int i = productImgMapper.insertSelective(productImgEntity);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK, id);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 删除商品滚动图
     *
     * @param productImgId
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult delProductImg(String productImgId) throws Exception {
        int i = productImgMapper.deleteByPrimaryKey(productImgId);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 新增产品规格
     *
     * @param productRemarkEntity
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult insertProductRemark(ProductRemarkEntity productRemarkEntity) throws Exception {
        String id = IdUtil.simpleUUID();
        productRemarkEntity.setRemarkId(id);
        int i = productRemarkMapper.insertSelective(productRemarkEntity);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK, productRemarkEntity);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 编辑产品规格
     *
     * @param productRemarkEntity
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult updateProductRemark(ProductRemarkEntity productRemarkEntity) throws Exception {
        int i = productRemarkMapper.updateByPrimaryKeySelective(productRemarkEntity);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 删除产品规格
     *
     * @param remarkId
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult delProductRemark(String remarkId) throws Exception {
        int i = productRemarkMapper.deleteByPrimaryKey(remarkId);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 新增商品类型管理
     *
     * @param productTypeEntity
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult insertProductType(ProductTypeEntity productTypeEntity) throws Exception {
        String id = IdUtil.simpleUUID();
        productTypeEntity.setProductTypeId(id);
        int i = productTypeMapper.insertSelective(productTypeEntity);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 删除商品一级类型
     *
     * @param productTypeId
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult delProductType(String productTypeId) throws Exception {
        int i = productTypeMapper.deleteByPrimaryKey(productTypeId);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 编辑商品一级类型
     *
     * @param productTypeEntity
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult updateProductType(ProductTypeEntity productTypeEntity) throws Exception {
        int i = productTypeMapper.updateByPrimaryKeySelective(productTypeEntity);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 新增二级类型
     *
     * @param productDetailType
     * @return
     * @throws Exception
     */
    public ResponseResult insertProductDetailType(ProductDetailTypeEntity productDetailType) throws Exception {
        int i = productDetailTypeMapper.insertSelective(productDetailType);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 删除二级类型
     *
     * @param productDetailId
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult delProductDetailType(String productDetailId) throws Exception {
        int i = productDetailTypeMapper.deleteByPrimaryKey(productDetailId);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 编辑二级类型
     *
     * @param productDetailType
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult updateProductDetailType(ProductDetailTypeEntity productDetailType) throws Exception {
        int i = productDetailTypeMapper.updateByPrimaryKeySelective(productDetailType);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 展示活动类型列表
     *
     * @return
     * @throws Exception
     */
    public ResponseResult ListProductActive() throws Exception {
        // 查询活动类型
        List<ProductActiveTypeEntity> productActiveTypeEntities = productActiveTypeMapper.selectAll();
        // 查询阈值
        for (ProductActiveTypeEntity productActiveTypeEntity : productActiveTypeEntities) {
            Example productActiveThresholdExample = new Example(ProductActiveThresholdEntity.class);
            productActiveThresholdExample.createCriteria().andEqualTo("activeTypeId", productActiveTypeEntity.getActiveTypeId());
            List<ProductActiveThresholdEntity> productActiveThresholdEntities = productActiveThresholdMapper.selectByExample(productActiveThresholdExample);
            // 放入与活动类型相关的阈值
            productActiveTypeEntity.setProductActiveThresholdEntities(productActiveThresholdEntities);
        }
        return new ResponseResult(ResponseMessage.OK, productActiveTypeEntities);
    }

    /**
     * 新增活动
     *
     * @param productActiveThresholdEntity
     * @return
     * @throws Exception
     */
    public ResponseResult insertActive(@RequestBody ProductActiveThresholdEntity productActiveThresholdEntity) throws Exception {
        int i = productActiveThresholdMapper.insertSelective(productActiveThresholdEntity);
        String title = productActiveThresholdEntity.getActiveName();
        String text = productActiveThresholdEntity.getThresholdExplain();
        // 向所有用户推送新增活动的消息
        PushMessageToAppDemo pushMessageToAppDemo = new PushMessageToAppDemo();
        pushMessageToAppDemo.pushMessageToApp(title,text);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 编辑活动类型
     *
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult updateProductActive(ProductActiveThresholdEntity productActiveThresholdEntity) throws Exception {
        // Integer activeTypeId = productActiveThresholdEntity.getActiveTypeId();
        // 买几送几、买xx件送xx元代金券、换购、基本信息
        int i = productActiveThresholdMapper.updateByPrimaryKeySelective(productActiveThresholdEntity);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 活动商品列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    public ResponseResult listActiveProduct(Integer pageNum, Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        // 查询拥有活动的商品规格
        List<ProductRemarkEntity> productRemarkEntities = productManagerMapper.getProductRemark();
        for (ProductRemarkEntity productRemarkEntity : productRemarkEntities) {
            // 查询阈值 放入阈值
            ProductActiveThresholdEntity productActiveThreshold = productActiveThresholdMapper.selectByPrimaryKey(productRemarkEntity.getThresholdId());
            productRemarkEntity.setProductActiveThresholdEntity(productActiveThreshold);
        }
        PageInfo<ProductRemarkEntity> productRemarkEntityPageInfo = new PageInfo<>(productRemarkEntities);
        return new ResponseResult(ResponseMessage.OK, productRemarkEntityPageInfo);
    }

    /**
     * 删除活动商品
     *
     * @param remarkId
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult delActiveProduct(String remarkId) throws Exception {
        Example productRemarkExample = new Example(ProductRemarkEntity.class);
        productRemarkExample.createCriteria().andEqualTo("remarkId", remarkId);
        // 修改商品threshold_id 为 0
        ProductRemarkEntity remarkEntity = new ProductRemarkEntity();
        remarkEntity.setThresholdId(0);
        int i = productRemarkMapper.updateByExampleSelective(remarkEntity, productRemarkExample);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 编辑活动商品
     *
     * @param updateActiveProductModel
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult updateActiveProduct(UpdateActiveProductModel updateActiveProductModel) throws Exception {
        DateTime begin = DateUtil.parse(updateActiveProductModel.getBeginTime(), "yyyy-MM-dd HH:mm:ss");
        DateTime end = DateUtil.parse(updateActiveProductModel.getEndTime(), "yyyy-MM-dd HH:mm:ss");
      /*  if (new Date().after(begin) && new Date().before(end)) {
            return new ResponseResult(ResponseMessage.FAIL, "活动已开始，不能编辑");
        }*/

        // 去除该商品的活动属性
        if (updateActiveProductModel.getOldRemarkId() != null && !("").equals(updateActiveProductModel.getOldRemarkId())) {
            ProductRemarkEntity remarkEntity = new ProductRemarkEntity();
            remarkEntity.setRemarkId(updateActiveProductModel.getOldRemarkId());
            remarkEntity.setThresholdId(0);
            productRemarkMapper.updateByPrimaryKeySelective(remarkEntity);
        }
        ProductRemarkEntity remark = new ProductRemarkEntity();
        remark.setRemarkId(updateActiveProductModel.getRemarkId());
        remark.setThresholdId(1);
        remark.setThresholdId(updateActiveProductModel.getThresholdId());
        // 是否可以拼单
        if (updateActiveProductModel.getShareBill() != null) {
            remark.setShareBill(updateActiveProductModel.getShareBill());
        }
        // 更改可拼单产品
        if (updateActiveProductModel.getShareBillRemarkId() != null) {
            remark.setShareBillRemarkId(updateActiveProductModel.getShareBillRemarkId());
        }
        // 更新换购商品id 或者赠品id
        if (updateActiveProductModel.getShareBillRemarkId() != null) {
            ProductActiveThresholdEntity productActiveThresholdEntity = new ProductActiveThresholdEntity();
            productActiveThresholdEntity.setThresholdId(updateActiveProductModel.getThresholdId());
            productActiveThresholdEntity.setTradRemarkId(updateActiveProductModel.getShareBillRemarkId());
            productActiveThresholdMapper.updateByPrimaryKeySelective(productActiveThresholdEntity);
        }
        int i = productRemarkMapper.updateByPrimaryKeySelective(remark);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 新增活动商品
     *
     * @param updateActiveProductModel
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult insertActiveProduct(UpdateActiveProductModel updateActiveProductModel) throws Exception {
        // 将该商品设为活动商品
        ProductRemarkEntity remark = new ProductRemarkEntity();
        remark.setRemarkId(updateActiveProductModel.getRemarkId());
        remark.setThresholdId(updateActiveProductModel.getThresholdId());
        // 是否可以拼单
        if (updateActiveProductModel.getShareBill() != null) {
            remark.setShareBill(updateActiveProductModel.getShareBill());
        }
        // 更改可拼单产品
        if (updateActiveProductModel.getShareBillRemarkId() != null) {
            remark.setShareBillRemarkId(updateActiveProductModel.getShareBillRemarkId());
        }
        int i = productRemarkMapper.updateByPrimaryKeySelective(remark);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 活动赠品列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    public ResponseResult listActiveGive(String key, Integer pageNum, Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        if (key != null && !("").equals(key)) {
            Example activeGiveExample = new Example(ProductActiveGiveEntity.class);
            activeGiveExample.createCriteria().andLike("giveName", "%" + key + "%");
            List<ProductActiveGiveEntity> productActiveGiveEntities = productActiveGiveMapper.selectByExample(activeGiveExample);
            PageInfo<ProductActiveGiveEntity> productActiveGiveEntityPageInfo = new PageInfo<>(productActiveGiveEntities);
            return new ResponseResult(ResponseMessage.OK, productActiveGiveEntityPageInfo);
        }

        List<ProductActiveGiveEntity> productActiveGiveEntities = productActiveGiveMapper.selectAll();
        PageInfo<ProductActiveGiveEntity> productActiveGiveEntityPageInfo = new PageInfo<>(productActiveGiveEntities);
        return new ResponseResult(ResponseMessage.OK, productActiveGiveEntityPageInfo);
    }

    /**
     * 新增赠品
     *
     * @param productActiveGiveEntity
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult insertActiveGive(ProductActiveGiveEntity productActiveGiveEntity) throws Exception {
        productActiveGiveEntity.setCreateTime(new Date());
        int i = productActiveGiveMapper.insertSelective(productActiveGiveEntity);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 删除活动赠品
     *
     * @param activeGiveId
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult delActiveGive(String activeGiveId) throws Exception {
        int i = productActiveGiveMapper.deleteByPrimaryKey(activeGiveId);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 编辑活动赠品
     *
     * @param productActiveGiveEntity
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult updateActiveGive(ProductActiveGiveEntity productActiveGiveEntity) throws Exception {
        int i = productActiveGiveMapper.updateByPrimaryKeySelective(productActiveGiveEntity);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 积分商品列表
     *
     * @param key
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    public ResponseResult listIntegralProduct(Integer integralTypeId, String key, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        // 查询积分商城列表
        List<IntegralEntity> integralEntities = null;
        Example integralExample = new Example(IntegralEntity.class);
        Example.Criteria criteria = integralExample.createCriteria();
        boolean result = false;
        if (integralTypeId != null) {
            result = true;
            criteria.andEqualTo("integralType", integralTypeId);
        } else if (key != null && !("").equals(key)) {
            result = true;
            criteria.andLike("integralName", "%" + key + "%");
        }
        if (result == true) {
            integralEntities = integralMapper.selectByExample(integralExample);
        } else {
            integralEntities = integralMapper.selectAll();
        }
        PageInfo<IntegralEntity> integralEntityPageInfo = new PageInfo<>(integralEntities);
        // 积分商城类型
        List<IntegralTypeEntity> integralTypeEntities = integralTypeMapper.selectAll();
        HashMap<String, Object> mm = new HashMap<>();
        mm.put("integralShop", integralEntityPageInfo);
        mm.put("integralType", integralTypeEntities);
        return new ResponseResult(ResponseMessage.OK, mm);
    }

    /**
     * 新增积分商品
     *
     * @param integralEntity
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult insertIntegralProduct(IntegralEntity integralEntity) throws Exception {
        int i = integralMapper.insertSelective(integralEntity);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 编辑积分商品
     *
     * @param integralEntity
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult updateIntegralProduct(IntegralEntity integralEntity) throws Exception {
        int i = integralMapper.updateByPrimaryKeySelective(integralEntity);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 删除积分商品
     *
     * @param integralId
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult delIntegralProduct(String integralId) throws Exception {
        int i = integralMapper.deleteByPrimaryKey(integralId);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 积分商品分类编辑
     *
     * @param integralTypeEntity
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult updateIntegralType(IntegralTypeEntity integralTypeEntity) throws Exception {
        integralTypeEntity.setUpdateTime(DateUtil.now());
        int i = integralTypeMapper.updateByPrimaryKeySelective(integralTypeEntity);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 积分商品分类新增
     *
     * @param integralTypeEntity
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult insertIntegralType(IntegralTypeEntity integralTypeEntity) throws Exception {
        integralTypeEntity.setCreateTime(DateUtil.now());
        integralTypeEntity.setUpdateTime(DateUtil.now());
        int i = integralTypeMapper.insertSelective(integralTypeEntity);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 运营数据
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     */
    public ResponseResult productStatistics(String startTime, String endTime, String status) throws Exception {
        //封装结果
        Map map = new HashMap();
        //判断时间不为空
        if (startTime != null && endTime != null && !"".equals(startTime) && !"".equals(endTime)) {
            List<ProductStatisticsModel> productShare = productMapper.findProductShare(startTime, endTime);
            List<IntegralStatisticsModel> integralShare = integralMapper.findIntegralShare(startTime, endTime);
            //日历
            List<CalendarEntity> calendarEntities = calendarMapper.selProductDateAll(startTime, endTime);
            for (CalendarEntity calendarEntity : calendarEntities) {
                //遍历productShareUserId
                for (ProductStatisticsModel productStatisticsModel : productShare) {
                    //获取时间
                    String recoverDate1 = productStatisticsModel.getRecoverDate();
                    Date date = DateUtil.parse(recoverDate1);
                    String format1 = DateUtil.format(date, "yyyy-MM-dd");
                    //对比日历的时间
                    if (format1.equals(calendarEntity.getDateList())) {
                        //得到分享数
                        String countShare = productStatisticsModel.getCountShare();
                        if (countShare != null && !"".equals(countShare)) {
                            Integer views = Integer.parseInt(countShare);
                            calendarEntity.setProductViews(views);
                        }
                    }
                }
                ////遍历integralShare
                for (IntegralStatisticsModel integralStatisticsModel : integralShare) {
                    //获取时间
                    String recoverDate2 = integralStatisticsModel.getRecoverDate();
                    Date date1 = DateUtil.parse(recoverDate2);
                    String format2 = DateUtil.format(date1, "yyyy-MM-dd");
                    //对比日历的时间
                    if (format2.equals(calendarEntity.getDateList())) {
                        //得到分享积分商品数
                        String countResearch = integralStatisticsModel.getCountShare();
                        if (countResearch != null && !"".equals(countResearch)) {
                            Integer i = Integer.parseInt(countResearch);
                            calendarEntity.setIntegralViews(i);
                        }
                    }
                }
                map.put("Statistics", calendarEntities);
            }
        }

        //status是O查询月数据
        if ("0".equals(status)) {
            //获取当前时间
            //当前时间字符串，格式：yyyy-MM-dd HH:mm:ss
            String now = DateUtil.now();

            //获取当前时间的前一个月
            Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
            ca.setTime(new Date()); // 设置时间为当前时间
            ca.add(Calendar.MONTH, -1);// 月份减1
            Date resultDate = ca.getTime(); // 结果
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(resultDate);
            List<ProductStatisticsModel> productShare = productMapper.findProductShare(format, now);

            List<IntegralStatisticsModel> integralShare = integralMapper.findIntegralShare(format, now);
            //日历
            List<CalendarEntity> calendarEntities = calendarMapper.selProductAll(format, now);

            for (CalendarEntity calendarEntity : calendarEntities) {
                //productShare
                for (ProductStatisticsModel productStatisticsModel : productShare) {
                    //获取时间
                    String recoverDate1 = productStatisticsModel.getRecoverDate();
                    Date date = DateUtil.parse(recoverDate1);
                    String format1 = DateUtil.format(date, "yyyy-MM-dd");
                    //对比日历的时间
                    if (format1.equals(calendarEntity.getDateList())) {
                        //得到分享数
                        String countShare = productStatisticsModel.getCountShare();
                        if (countShare != null && !"".equals(countShare)) {
                            Integer views = Integer.parseInt(countShare);
                            calendarEntity.setProductViews(views);
                        }
                    }
                }
                ////遍历integralShare
                for (IntegralStatisticsModel integralStatisticsModel : integralShare) {
                    //获取时间
                    String recoverDate2 = integralStatisticsModel.getRecoverDate();
                    Date date1 = DateUtil.parse(recoverDate2);
                    String format2 = DateUtil.format(date1, "yyyy-MM-dd");
                    //对比日历的时间
                    if (format2.equals(calendarEntity.getDateList())) {
                        //得到分享积分商品数
                        String countResearch = integralStatisticsModel.getCountShare();
                        if (countResearch != null && !"".equals(countResearch)) {
                            Integer i = Integer.parseInt(countResearch);
                            calendarEntity.setIntegralViews(i);
                        }
                    }
                }
                map.put("Statistics", calendarEntities);
            }
        }
        //status是O查询月数据
        if ("1".equals(status)) {
            //获取当前时间
            //当前时间字符串，格式：yyyy-MM-dd HH:mm:ss
            String now = DateUtil.now();
            //获取当前时间的前一年
            Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
            ca.setTime(new Date()); // 设置时间为当前时间
            ca.add(Calendar.YEAR, -1); // 年份减1
            Date resultDate = ca.getTime(); // 结果
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(resultDate);
            //获取这一年时间段的所有帖子，根据帖子创建时间查询每月的商品分享数
            List<ProductStatisticsModel> productShare = productMapper.findProductRecoverDateYear(format, now);

            //获取这一年时间段的所有帖子，根据帖子创建时间查询每月的积分商品分享数
            List<IntegralStatisticsModel> integralRecoverDateYear = integralMapper.findIntegralRecoverDateYear(format, now);

            //日历
            List<CalendarEntity> calendarEntities = calendarMapper.selProductAllYear(format, now);
            for (CalendarEntity calendarEntity : calendarEntities) {
                for (ProductStatisticsModel productStatisticsModel : productShare) {
                    String dateList = calendarEntity.getDateList();
                    Date date1 = DateUtil.parse(dateList);
                    String format3 = DateUtil.format(date1, "yyyy-MM");
                    calendarEntity.setYear(format3);
                    //获取时间进行对比
                    String recoverDate1 = productStatisticsModel.getRecoverDate();
                    Date date = DateUtil.parse(recoverDate1);
                    String format1 = DateUtil.format(date, "yyyy-MM");
                    if (format1.equals(calendarEntity.getYear())) {
                        System.err.println(productStatisticsModel.getCountShare());
                        calendarEntity.setProductViews(Integer.parseInt(productStatisticsModel.getCountShare()));
                    }
                }
                for (IntegralStatisticsModel integralStatisticsModel : integralRecoverDateYear) {
                    //获取时间进行对比
                    String integralRecoverDate = integralStatisticsModel.getRecoverDate();
                    Date date2 = DateUtil.parse(integralRecoverDate);
                    String str = DateUtil.format(date2, "yyyy-MM");
                    if (str.equals(calendarEntity.getYear())) {
                        calendarEntity.setIntegralViews(Integer.parseInt(integralStatisticsModel.getCountShare()));
                    }
                }
            }
            map.put("Statistics", calendarEntities);
        }
        return new ResponseResult(ResponseMessage.OK, map);
    }

    /**
     * 商品页分享次数统计
     *
     * @param startTime
     * @param endTime
     * @param status    0 时，1 天，2 月
     * @return
     * @throws Exception
     */
    public ResponseResult productShareStatistics(String startTime, String endTime, Integer status, Integer communityType, String communityId) throws Exception {

        List<HashMap<String, Long>> result = new ArrayList<>();
        String[] hoursArray = {"00", "02", "04", "06", "08", "10", "12", "14", "16", "18", "20", "22", "00"};
        List<String> hours = Arrays.asList(hoursArray);
        if (status == 0) {
            // 按小时统计商品页分享次数（每两个小时一个阶段）
            List<HashMap<String, String>> shareHour = new ArrayList<>();
            if (startTime == null || ("").equals(startTime) || endTime == null || ("").equals(endTime)) {
                Date date = new Date();
                String format = DateUtil.format(date, "yyyy-MM-dd");
                for (int i = 1; i < hours.size(); i++) {
                    HashMap<String, String> mm = new HashMap<>();
                    startTime = format + " " + hours.get(i - 1);
                    endTime = format + " " + hours.get(i);
                    Integer num = productManagerMapper.productShareHour(startTime, endTime, communityType, communityId);
                    if (num == null) {
                        mm.put("num", "0");
                        mm.put("hour", format + " " + hours.get(i - 1) + "-" + hours.get(i));
                        shareHour.add(mm);
                    } else {
                        mm.put("num", num + "");
                        mm.put("hour", format + " " + hours.get(i - 1) + "-" + hours.get(i));
                        shareHour.add(mm);
                    }
                }
                return new ResponseResult(ResponseMessage.OK, shareHour);

            } else {
                for (int i = 1; i < hours.size(); i++) {
                    HashMap<String, String> mm = new HashMap<>();
                    String start = startTime + " " + hours.get(i - 1);
                    String end = endTime + " " + hours.get(i);
                    Integer num = productManagerMapper.productShareHour(start, end, communityType, communityId);
                    if (num == null) {
                        mm.put("num", "0");
                        mm.put("hour", startTime + " " + hours.get(i - 1) + "-" + hours.get(i));
                        shareHour.add(mm);
                    } else {
                        mm.put("num", num + "");
                        mm.put("hour", startTime + " " + hours.get(i - 1) + "-" + hours.get(i));
                        shareHour.add(mm);
                    }
                }
                return new ResponseResult(ResponseMessage.OK, shareHour);
            }

        } else if (status == 1) {
            // 按照天统计商品页分享次数
            if (startTime == null || ("").equals(startTime) || endTime == null || ("").equals(endTime)) {
                // 当前天往前推一个月
                endTime = DateUtil.now();
                // 获取当前时间的前一个月
                Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
                ca.setTime(new Date()); // 设置时间为当前时间
                ca.add(Calendar.MONTH, -1);// 月份减1
                Date resultDate = ca.getTime(); // 结果
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                startTime = sdf.format(resultDate);
                result = productManagerMapper.productShareDay(startTime, endTime, communityType, communityId);
                return new ResponseResult(ResponseMessage.OK, result);
            } else {
                result = productManagerMapper.productShareDay(startTime, endTime, communityType, communityId);
                return new ResponseResult(ResponseMessage.OK, result);
            }
        } else if (status == 2) {
            // 按照月份统计
            if (startTime == null || ("").equals(startTime) || endTime == null || ("").equals(endTime)) {
                Calendar c = Calendar.getInstance();
                c.add(Calendar.MONTH, -4);
                String before_six = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH);//六个月前
                ArrayList<String> months = new ArrayList<String>();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");// 格式化为年月
                Calendar min = Calendar.getInstance();
                Calendar max = Calendar.getInstance();
                min.setTime(sdf.parse(before_six));
                min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
                max.setTime(sdf.parse(sdf.format(new Date())));
                max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
                Calendar curr = min;
                while (curr.before(max)) {
                    months.add(sdf.format(curr.getTime()));
                    curr.add(Calendar.MONTH, 1);
                }
                startTime = months.get(0);
                endTime = months.get(months.size() - 1);
                // 数据查询的数据每一天重复一条，需要减去
                result = productManagerMapper.productShareMonth(startTime, endTime, communityType, communityId);
                for (HashMap<String, Long> mm : result) {
                    String month = mm.get("month") + "";
                    DateTime dateMonth = DateUtil.parse(month, "yyyy-MM");
                    c.setTime(dateMonth);
                    // 得到当月天数
                    int actualMaximum = c.getActualMaximum(Calendar.DAY_OF_MONTH);
                    Integer integer = mm.get("num").intValue();
                    // 覆盖原来查询的数据
                    mm.put("num", Long.valueOf(integer - actualMaximum));
                }
                return new ResponseResult(ResponseMessage.OK, result);
            } else {
                // 按照月统计商品页分享次数
                result = productManagerMapper.productShareMonth(startTime, endTime, communityType, communityId);
                for (HashMap<String, Long> mm : result) {
                    Calendar c = Calendar.getInstance();
                    String month = mm.get("month") + "";
                    DateTime dateMonth = DateUtil.parse(month, "yyyy-MM");
                    c.setTime(dateMonth);
                    // 得到当月天数
                    int actualMaximum = c.getActualMaximum(Calendar.DAY_OF_MONTH);
                    Integer integer = mm.get("num").intValue();
                    // 覆盖原来查询的数据
                    mm.put("num", Long.valueOf(integer - actualMaximum));
                }
                return new ResponseResult(ResponseMessage.OK, result);
            }
        }
        return new ResponseResult(ResponseMessage.FAIL, "status为未知值");
    }
}
